<?php
/**
 * ===============================================
 * 版权所有 2019-2050 青岛铁锤科技有限公司，并保留所有权利。
 * 网站地址: http://www.huaxianling.com
 * ===============================================
 * Author: Rag Hu
 * Created Time: 2019/8/24 21:54
 * Modified Time: 2019/8/24 21:54
 * Version: 2.0
 */

namespace App\Modules\MemberCard\Criterias;


use Flower\Core\Repository\Contracts\RepositoryInterface;
use Flower\Core\Repository\Criterias\BaseCriterias;

class GetMemberCardByCardTypeCriteria extends BaseCriterias
{
    protected $card_type_id;

    public function __construct($card_type_id)
    {
        $this->card_type_id = $card_type_id;
    }

    public function apply($model, RepositoryInterface $repository)
    {
        $card_type_id = $this->card_type_id;

        return $model
            ->select([
                'member_card_flow.id',
                'member_card_flow.user_id',
                'member_card_flow.card_id',
                'member_card_flow.created_at',
                'member_card_flow.payment',
                'member_card_flow.type',
                'member_card_flow.real_amount'

            ])
            ->leftJoin('member_card', 'card_id', 'member_card.id')
            ->leftJoin('user', 'member_card.user_id', 'user.id')
            ->with(['card' => function ($query) {
                $query->select([
                    'member_card.id',
                    'member_card.name',
                    'member_card.mobile',
                    'member_card.user_id',
                    'member_card.count',
                    'member_card.balance',
                    'member_card.attribute',
                ]);
            }])
            ->with(['royalty' => function ($query) {
                $query->select(['amount', 'item_id'])->where('type', 2);
            }])
            ->with(['user' => function ($query) {
                $query->select(['id', 'nick']);
            }])
            ->where(function ($query) {
                $query->where('type', 1)
                    ->orWhere('type', 4);
            })
            ->where('member_card.type_id', $card_type_id)
            ->orderBy('member_card_flow.id', 'DESC');
    }
}